package com.schoolhelper.post.controller;

import com.schoolhelper.post.domain.Post;
import com.schoolhelper.post.service.PostService;
import com.schoolhelper.utils.Result;
import com.schoolhelper.config.FileUploadConfig;
import org.springframework.security.core.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/posts")
@CrossOrigin(origins = "http://localhost:8080")  // 添加跨域支持
public class PostController {

    private static final Logger logger = LoggerFactory.getLogger(PostController.class);

    @Autowired
    private PostService postService;

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FileUploadConfig fileUploadConfig;

    // 获取帖子列表
    @GetMapping
    public Result<ArrayList<Post>> getAllPosts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size){
        // 计算偏移量
        int offset = (page - 1) * size;
        try {
            ArrayList<Post> allPosts = postService.getAllPostsWithPagination(page, size);
            
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            logger.info("Authentication对象: {}", authentication);
            Long currentUserId = null;
            if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                logger.info("用户详情: {}", userDetails.getUsername());
                try {
                    currentUserId = Long.valueOf(userDetails.getUsername());
                    logger.info("解析到的用户ID: {}", currentUserId);
                } catch (NumberFormatException e) {
                    logger.warn("无法解析用户ID: {}", userDetails.getUsername());
                }
            } else {
                logger.warn("用户未认证或认证信息无效");
            }
            
            // 为每个帖子设置isLiked状态和处理头像URL
            for (Post post : allPosts) {
                // 处理头像URL
                if (post.getAvatar() != null && !post.getAvatar().isEmpty()) {
                    // 如果头像不是完整URL，则拼接完整URL
                    if (!post.getAvatar().startsWith("http")) {
                        post.setAvatar(fileUploadConfig.getFileUrl(post.getAvatar()));
                    }
                }
                
                // 设置点赞状态
                if (currentUserId != null) {
                    boolean isLiked = postService.isPostLikedByUser(post.getId(), currentUserId);
                    logger.info("帖子ID: {}, 用户ID: {}, 点赞状态: {}", post.getId(), currentUserId, isLiked);
                    post.setIsLiked(isLiked);
                } else {
                    logger.info("帖子ID: {}, 用户未登录，设置isLiked为false", post.getId());
                    post.setIsLiked(false);
                }
            }
            
            return Result.success(allPosts);
        } catch (Exception e) {
            logger.error("获取帖子列表失败", e);
            return Result.error("获取帖子列表失败: " + e.getMessage());
        }
    }

    // 根据用户ID获取帖子列表
    @GetMapping("/user/{userId}")
    public Result<ArrayList<Post>> getPostsByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size){
        try {
            logger.info("获取用户ID为{}的帖子列表，页码：{}，每页数量：{}", userId, page, size);
            ArrayList<Post> userPosts = postService.getPostsByUserIdWithPagination(userId, page, size);
            
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Long currentUserId = null;
            if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                try {
                    currentUserId = Long.valueOf(userDetails.getUsername());
                } catch (NumberFormatException e) {
                    logger.warn("无法解析用户ID: {}", userDetails.getUsername());
                }
            }
            
            // 为每个帖子设置isLiked状态和处理头像URL
            for (Post post : userPosts) {
                // 处理头像URL
                if (post.getAvatar() != null && !post.getAvatar().isEmpty()) {
                    // 如果头像不是完整URL，则拼接完整URL
                    if (!post.getAvatar().startsWith("http")) {
                        post.setAvatar(fileUploadConfig.getFileUrl(post.getAvatar()));
                    }
                }
                
                // 设置点赞状态
                if (currentUserId != null) {
                    boolean isLiked = postService.isPostLikedByUser(post.getId(), currentUserId);
                    post.setIsLiked(isLiked);
                } else {
                    post.setIsLiked(false);
                }
            }
            
            return Result.success(userPosts);
        } catch (Exception e) {
            logger.error("获取用户帖子列表失败", e);
            return Result.error("获取用户帖子列表失败: " + e.getMessage());
        }
    }
    // 创建帖子
    @PostMapping
    public Result<Post> createPost(@ModelAttribute Post post, @RequestParam(value = "images", required = false) MultipartFile[] images) throws IOException {
        logger.info("进入创建帖子方法");
        // 获取当前登录用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        logger.info("Authentication object: {}", authentication);
        if (authentication == null) {
            logger.error("Authentication is null");
            return Result.error("用户未认证");
        }
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        logger.info("User details: {}", userDetails);
        String username = userDetails.getUsername();
        logger.info("Extracted username: {}", username);
        Long userId;
        try {
            userId = Long.valueOf(username);
        } catch (NumberFormatException e) {
            return Result.error("用户信息解析失败");
        }
        post.setUserId(userId);
        logger.info("收到的帖子标题: {}", post.getTitle());
        post.setTitle(post.getTitle().trim());
        post.setCreateTime(new Date());
        post.setLikeCount(0);
        post.setCommentCount(0);
        if (post.getContent() == null || post.getContent().trim().isEmpty()) {
            return Result.error("帖子内容不能为空");
        }
        // 处理图片上传逻辑（如有）
        List<String> imageUrls = new ArrayList<>();
        if (images != null && images.length > 0) {
            // 获取项目根目录下的 uploads 目录
            String uploadDir = System.getProperty("user.dir") + File.separator + "uploads";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            for (MultipartFile image : images) {
                if (!image.isEmpty()) {
                    String fileName = System.currentTimeMillis() + "_" + image.getOriginalFilename();
                    File dest = new File(dir, fileName);
                    image.transferTo(dest);
                    // 构建完整的图片URL
                    String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
                    imageUrls.add(baseUrl + "/uploads/" + fileName);
                }
            }
        }
        // 将图片路径传递给 service 层
        post.setImageUrls(imageUrls);
        try {
            logger.info("postService是否为null: {}", postService == null);
            logger.info("调用服务前的帖子对象: {}", post);
            logger.info("准备调用postService.createPost");
            Post createdPost = postService.createPost(post);
            return Result.success(createdPost);
        } catch (Exception e) {
            logger.error("创建帖子失败", e);
            return Result.error("创建帖子失败: " + e.getMessage());
        }
    }
    // 点赞帖子
    @PostMapping("/{postId}/like")
    public Result<String> likePost(@PathVariable Long postId) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
                return Result.error("用户未认证");
            }
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Long userId = Long.valueOf(userDetails.getUsername());
            
            boolean success = postService.likePost(postId, userId);
            if (success) {
                return Result.success("点赞成功");
            } else {
                return Result.error("已经点过赞了");
            }
        } catch (Exception e) {
            logger.error("点赞失败", e);
            return Result.error("点赞失败: " + e.getMessage());
        }
    }

    // 取消点赞
    @PostMapping("/{postId}/unlike")
    public Result<String> unlikePost(@PathVariable Long postId) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
                return Result.error("用户未认证");
            }
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Long userId = Long.valueOf(userDetails.getUsername());
            
            boolean success = postService.unlikePost(postId, userId);
            if (success) {
                return Result.success("取消点赞成功");
            } else {
                return Result.error("还未点赞");
            }
        } catch (Exception e) {
            logger.error("取消点赞失败", e);
            return Result.error("取消点赞失败: " + e.getMessage());
        }
    }
}
